const { DB } = require('./sqlite3');

const MouseDao = {
    logPos(posStack, callback) {
        let stmt = DB.prepare("INSERT INTO mouse_pos (pos , c_time) VALUES ( ? , ? )");
        stmt.run([JSON.stringify(posStack), Date.now()], () => {
            console.log('Save posStack', posStack.length);
            typeof callback === "function" && callback();
        });
    },
    getAllPos(callback) {
        DB.all("SELECT id,pos,c_time,note FROM mouse_pos", (err, rows) => {
            typeof callback === "function" && callback(rows);
        });
    },
    getPosById(id, callback) {
        DB.get("SELECT id,pos,c_time,note FROM mouse_pos WHERE id = " + id, (err, row) => {
            if (!err) {
                typeof callback === "function" && callback(row);
                return;
            }
            console.error(err);
        });
    },
    delPosById(id, callback) {
        DB.run('DELETE FROM mouse_pos WHERE id = ' + id, (rtn, err) => {
            if (!err) {
                typeof callback === "function" && callback(rtn);
                return;
            }
            console.error(err);
        });
    },
    altPosNote({ id, note }, callback) {
        DB.run('UPDATE mouse_pos SET note = ? WHERE id = ?', [note, id], (rtn, err) => {
            if (!err) {
                // console.log('Update Success ', { id, note });
                typeof callback === "function" && callback(rtn);
                return;
            }
            console.error(err);
        });
    },
    getLastPos(callback) {
        DB.get("SELECT id,pos,c_time,note FROM mouse_pos ORDER BY id DESC ", (err, row) => {
            if (!err) {
                typeof callback === "function" && callback(row);
                return;
            }
            console.error(err);
        });
    },
}

module.exports.MouseDao = MouseDao;